package com.jagochan.imchat.module.wx.controller;

import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

@Slf4j
@AllArgsConstructor
@RestController
@RequestMapping("wx/portal/test")
public class WxPortalTestController {
    private final WxMpService wxService;

    /**
     * 获取临时二维码票证
     *
     * @param code 场景值ID（字符串形式的ID），字符串类型，长度限制为1到64
     * @return 二维码票证URL
     */
    @GetMapping(value = "/createTmpTicket", produces = MediaType.IMAGE_PNG_VALUE)
    public byte[] testQrCodeCreateTmpTicket(@RequestParam String code) throws WxErrorException {
        // 生成临时二维码Ticket
        WxMpQrCodeTicket wxMpQrCodeTicket = wxService.getQrcodeService().qrCodeCreateTmpTicket(code, 60 * 10);
        String qrCodeUrl = wxMpQrCodeTicket.getUrl();

        // 配置二维码参数
        QrConfig config = new QrConfig(200, 200);

        // 使用Hutool生成二维码并输出到字节数组
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            QrCodeUtil.generate(qrCodeUrl, config, "png", outputStream);
            return outputStream.toByteArray();
        } catch (Exception e) {
            // 实际项目中应该有更完善的异常处理
            e.printStackTrace();
            return new byte[0];
        }
    }

}